/*加载mysql模块*/
const mysql = require("mysql2");
/*建立数据库连接*/
const connection = mysql.createConnection({
    host:"localhost",
    port:3307,/*默认是3306*/
    user:"root",
    password:"root",
    database:"cangku_xh_21"
});
/*打开连接*/
connection.connect();

const query = (sql,objs=[])=>{
    return new Promise((resolve, reject)=>{
        connection.query(sql,objs,function (e,r,t) {
            if(e){
                reject(e);
            }
            if(t){//第三个参数存在则为查询操作
                const result = [];
                /*遍历结果集获取所有数据*/
                for(const d of r){
                    /*初始化存储对象*/
                    const map = {};
                    /*遍历对象的key*/
                    for(const key in d){
                        /*判断是否包含下划线*/
                        if(key.includes("_")){
                            /*拆分字符串*/
                            const word = key.split("_");
                            /*初始化处理后的key*/
                            let k = word[0];
                            /*遍历剩余部分字段*/
                            for(let i=1;i<word.length;i++){
                                /*获取后续的单词*/
                                let w = word[i].substring(0,1).toUpperCase()+word[i].substring(1);
                                k+=w;
                            }
                            map[k]=d[key];
                        }else{
                            map[key]=d[key];
                        }
                    }
                    result.push(map);
                }
                resolve(result);
            }else{
                resolve(r.insertId);
            }
        })
    })

}

module.exports = query
